<?php

namespace app\api\job;

use app\common\model\ScoreLog;
use app\common\model\User;
use think\queue\Job;


/**
 * 抢购订单自动操作
 */
class RushOrderAutoOper extends BaseJob
{
    /**
     * 订单自动取消
     */
    public function autoCancel(Job $job, $data){
        try {
            $order_id = $data['order_id'];
            $order = \app\api\model\RushOrder::get($order_id);
            if ($order && $order['order_status'] == '0') {
                \think\Db::transaction(function () use ($order) {
                    \app\api\controller\RushBuyer::cancelAction($order);
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoClose' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    /**
     * 订单自动确认收款
     */
    public function autoConfirmGetMoney(Job $job, $data){
        try {
            $order_id = $data['order_id'];
            $order = \app\api\model\RushOrder::get($order_id);
            if ($order && $order['order_status'] == '1') {
                \think\Db::transaction(function () use ($order) {
                    \app\api\controller\RushSeller::confirmGetMoneyAction($order);
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoConfirmGetMoney' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    /**
     * 自动发送积分
     */
    public function autoSendScore(Job $job, $data){
        try {
            $order_id = $data['order_id'];
            $order = \app\api\model\RushOrder::get($order_id);
            if ($order) {
                \think\Db::transaction(function () use ($order) {
                    //分销积分状态变为已结算，并增加用户表积分
                    $score_logs = ScoreLog::where('rush_order_id',$order['id'])->select();
                    foreach ($score_logs as $log){
                        User::where('id',$log['user_id'])->setInc('score',$log['score']);
                        $log->save(['is_settled'=>'1']);
                    }
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoSendScore' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }
}
